package com.zznzzn.myweb.controller;


import com.zznzzn.myweb.exceptions.ServiceException;
import com.zznzzn.myweb.pojo.Receiving;
import com.zznzzn.myweb.pojo.RespModel;
import com.zznzzn.myweb.pojo.User;
import com.zznzzn.myweb.service.ReceivingService;
import com.zznzzn.myweb.service.UserService;
import com.zznzzn.myweb.util.Base64Util;
import com.zznzzn.myweb.util.JWTUtil;
import com.zznzzn.myweb.util.RespHelper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Api("Apis on /user")
@CrossOrigin
@RestController
@RequestMapping("/api/user")
//@SessionAttributes("user")//将model中user存入session
public class UserController {

    //    @Autowired
//    private RsaKeyProperties keys;
    @Autowired
    private UserService userService;

    @Autowired
    private ReceivingService receivingService;


    @PostMapping("/login")
    public RespModel<User> login(
            @RequestParam("username") String busername, @RequestParam("password") String bpassword,HttpServletRequest request) {
        String username = Base64Util.decode(busername);
        String password = Base64Util.decode(bpassword);

        User u = new User();
        u.setUsername(username);
        u.setPassword(password);
        try {
            User user1 = userService.login(u);
//            model.addAttribute("user",user1);
            request.getSession().setAttribute("user",u);
            return RespHelper.buildSuccess("登录成功", user1);
        } catch (Exception e) {
            return RespHelper.buildFailure(e.getMessage());
        }

    }

    @PostMapping("/checkUname")
    public RespModel<Object> checkUserName(@RequestParam("username") String busername) {

        boolean hasUser = userService.checkUsername(Base64Util.decode(busername));
//        System.out.println(Base64Util.decode(busername));
        if (hasUser) {
            return RespHelper.buildFailure("该账号已存在");
        } else {
            return RespHelper.buildSuccess("success");
        }
//        return  JSON.toJSONString(resp);
    }

    @PostMapping("/newUser")
    public RespModel<User> newUser(
            @RequestParam("username") String busername, @RequestParam("nickname") String bnickname,
            @RequestParam("password") String bpassword) {

        String username = null;
        String nickname = null;
        String password = null;
        try {
            username = Base64Util.fullDecode(busername);
            nickname = Base64Util.fullDecode(bnickname);
            password = Base64Util.fullDecode(bpassword);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        User u = new User();
        u.setUsername(username);
        u.setNickname(nickname);
        u.setPassword(password);

        try {
            User user1 = userService.addUser(u);
            return RespHelper.buildSuccess("创建成功", user1);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/flush")
    public RespModel<User> flush(HttpServletRequest request) {
        String token = request.getHeader(JWTUtil.AUTH_HEADER_KEY);
        if (token != null) {
            try {
                User u = userService.getUserById(JWTUtil.getUserId(token));

                if (JWTUtil.verify(token, u.getUuid(), u.getSalt()) && !JWTUtil.isExpiration(token)) {
                    u.setSalt("");
                    u.setPassword("");
                    request.getSession().setAttribute("user",u);
                    return RespHelper.buildSuccess("刷新用户信息成功", u);
                } else {
                    return RespHelper.buildUnauthorizated();
                }
            } catch (ServiceException e) {
                return RespHelper.buildFailure(e.getMessage());
            }
        } else {
            return RespHelper.buildUnauthorizated();
        }
    }

    @PostMapping("/updateProfile")
    public RespModel<User> updateProfile(
            @RequestParam("uuid") String uuid, @RequestParam("nickname") String bnickname,
            @RequestParam("gender") Integer gender, @RequestParam("desc") String bdesc,
            @RequestParam("email") String bemail
    ) {
        String nickname = "";
        String desc = "";
        String email = "";
        try {
            nickname = Base64Util.fullDecode(bnickname);
            desc = Base64Util.fullDecode(bdesc);
            email = Base64Util.fullDecode(bemail);


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            User user = userService.getUserById(uuid);
            user.setNickname(nickname);
            user.setDescription(desc);
            user.setGender(gender);
            user.setEmail(email);
            userService.updateUser(user);

            return RespHelper.buildSuccess("修改信息成功!", userService.harmless(user));
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/addReceiving")
    public RespModel<Receiving> addReceiving(
            @RequestParam("uuid") String uuid, @RequestParam("name") String bname,
            @RequestParam("phone") String bphone, @RequestParam("address") String baddress,
            @RequestParam("detail") String bdetail, @RequestParam("province") int province,
            @RequestParam("city") int city, @RequestParam("area") int area, @RequestParam("town") int town
    ) {
        String name = "";
        String phone = "";
        String address = "";
        String detail = "";
        try {
            name = Base64Util.fullDecode(bname);
            phone = Base64Util.fullDecode(bphone);
            address = Base64Util.fullDecode(baddress);
            detail = Base64Util.fullDecode(bdetail);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String receid = Base64Util.newUUID();

        try {
            Receiving receiving = new Receiving(receid, uuid, province, city, area, town, address, detail, name, phone);
            receivingService.addReceiving(receiving);

            return RespHelper.buildSuccess("增加收件地址成功", receiving);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/updateReceiving")
    public RespModel<Receiving> updateReceiving(
            @RequestParam("uuid") String uuid, @RequestParam("name") String bname,
            @RequestParam("phone") String bphone, @RequestParam("address") String baddress,
            @RequestParam("detail") String bdetail, @RequestParam("province") int province,
            @RequestParam("city") int city, @RequestParam("area") int area, @RequestParam("town") int town,
            @RequestParam("receid") String receid
    ) {
        String name = "";
        String phone = "";
        String address = "";
        String detail = "";
        try {
            name = Base64Util.fullDecode(bname);
            phone = Base64Util.fullDecode(bphone);
            address = Base64Util.fullDecode(baddress);
            detail = Base64Util.fullDecode(bdetail);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            Receiving receiving = new Receiving(receid, uuid, province, city, area, town, address, detail, name, phone);
            receivingService.updateReceiving(receiving);

            return RespHelper.buildSuccess("修改收件地址成功", receiving);
        } catch (ServiceException e) {
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/getReceivings")
    public RespModel<Object> getReceivings(@RequestParam("uuid") String uuid) {
        try {
            List<Receiving> receivings = receivingService.getReceivingByUid(uuid);
            return RespHelper.buildSuccess("获取成功",receivings);
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/getReceCount")
    public RespModel<Object> getReceCount(@RequestParam("uuid") String uuid,HttpServletRequest request) {
        try {
            int count = receivingService.getReceCount(uuid);
            return RespHelper.buildSuccess("获取成功",count);
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/delReceiving")
    public RespModel<Object> delReceiving(@RequestParam("receid") String receid) {
        try {
            receivingService.deleteReceiving(receid);

            return RespHelper.buildSuccess("删除成功");
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }

    @PostMapping("/getUserInfo")
    public RespModel<Object> getUserInfo(@RequestParam("uuid") String uuid){
        try{
            User user = userService.getUserById(uuid);
            return RespHelper.buildSuccess("获取成功",userService.harmless(user));
        }catch (ServiceException e){
            return RespHelper.buildFailure(e.getMessage());
        }
    }
}
